package com.linran.poll.service.impl;

import com.linran.poll.service.ILongPollingService;
import com.linran.poll.service.lock.LockPullTask;
import com.linran.poll.service.lock.LockPushTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

@Slf4j
@Service
public class LockLongPollingServiceImpl implements ILongPollingService {
    @Autowired
    private ScheduledExecutorService schedule;
    private LockPullTask lockPullTask;
    private Object lock;

    @PostConstruct
    public void post() {
        lock = new Object();
    }

    @Override
    public String pull() {
        lockPullTask = new LockPullTask(lock);
        Future<String> result = schedule.submit(lockPullTask);
        try {
            return result.get(10, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            /*不应该在异常中进行流程控制，所以有了方式三(Nacos的配置中心实现方式)*/
            log.info("拉取消息超时 {}", e.getMessage());
            synchronized (lock) {
                /*超时唤醒*/
                lock.notifyAll();
                lockPullTask.setData("timeout");
            }
            return "timeout";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ex";
    }

    @Override
    public String push(String data) {
        ScheduledFuture<String> future = this.schedule.schedule(new LockPushTask(lockPullTask, data, lock), 0, TimeUnit.SECONDS);
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ex";
    }
}
